<template>
  <page-header-wrapper :title="false">
    <a-card title="库存统计详情">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.keyword" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="品牌">
                <a-select v-model="queryParam.gdBrandId">
                  <a-select-option :value="i.id" v-for="i in brandOption" :key="i.id">{{ i.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="分类">
                  <a-select v-model="queryParam.classId">
                    <a-select-option :value="i.id" v-for="i in classifyOption" :key="i.id">{{
                      i.name
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- <div class="table-operator">
        <a-button type="primary">导出</a-button>
      </div> -->
      <a-card
        style="margin-top: 24px"
        size="small"
        :tabList="operationTabList"
        :activeTabKey="operationActiveTabKey"
        @tabChange="
          (key) => {
            this.operationActiveTabKey = key
            handleSearch(queryParam)
          }
        "
      >
        <a-table
          v-if="operationActiveTabKey === '1'"
          rowKey="key"
          :columns="columns"
          :data-source="loadData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: `${columns.length}0%` }"
          :footer="handleFooterShow ?? null"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
            </template>
          </span>
        </a-table>
        <a-table
          v-if="operationActiveTabKey === '2'"
          rowKey="key"
          :columns="namecolumns"
          :data-source="loadData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: `${namecolumns.length}0%` }"
          :footer="handleFooterShow ?? null"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
            </template>
          </span>
        </a-table>
        <a-table
          v-if="operationActiveTabKey === '3'"
          rowKey="key"
          :columns="suppliercolumns"
          :data-source="loadData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: `${suppliercolumns.length}0%` }"
          :footer="handleFooterShow ?? null"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
            </template>
          </span>
        </a-table>
        <a-table
          v-if="operationActiveTabKey === '4'"
          rowKey="key"
          :columns="channelcolumns"
          :data-source="loadData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: `${channelcolumns.length}0%` }"
          :footer="handleFooterShow ?? null"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
            </template>
          </span>
        </a-table>
        <a-table
          v-if="operationActiveTabKey === '5'"
          rowKey="key"
          :columns="brandcolumns"
          :data-source="loadData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: `${brandcolumns.length}0%` }"
          :footer="handleFooterShow ?? null"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
            </template>
          </span>
        </a-table>
        <a-table
          v-if="operationActiveTabKey === '6'"
          rowKey="key"
          :columns="classifycolumns"
          :data-source="loadData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: `${classifycolumns.length}0%` }"
          :footer="handleFooterShow ?? null"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
            </template>
          </span>
        </a-table>
      </a-card>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { getGdBrandListUsingPOST, getGdClassListUsingPOST } from '@/api/api/shangpinguanli.ts'
import { getPageSummaryUsingGET, getPageGoodsSummaryUsingGET, exportSummaryUsingPOST } from '@/api/api/kucunguanli.ts'
export default {
  name: 'StoreShopDetail',
  components: {},
  data() {
    return {
      operationTabList: [
        { key: '1', tab: '柜组统计' },
        { key: '2', tab: '商品名统计' },
        { key: '3', tab: '供应商统计' },
        { key: '4', tab: '渠道统计' },
        { key: '5', tab: '品牌汇总' },
        { key: '6', tab: '分类汇总' },
      ],
      operationActiveTabKey: '1',
      mdl: null,
      priceMdl: null,
      visible: false,
      priceVisible: false,
      value: '',
      confirmLoading: false,
      priceLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
        gdBrandId: '',
        classId: '',
      },
      // 表头
      columns: [
        {
          title: '柜组',
          dataIndex: 'name',
        },
        {
          title: '库存',
          dataIndex: 'count',
        },
        {
          title: '库存成本(元)',
          dataIndex: 'sum',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      namecolumns: [
        {
          title: '商品名',
          dataIndex: 'goodName',
        },
        {
          title: '商品码',
          dataIndex: 'code',
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
        },
        {
          title: '一级分类',
          dataIndex: 'topName',
        },
        {
          title: '二级分类',
          dataIndex: 'subName',
        },
        {
          title: '库存',
          dataIndex: 'count',
        },
        {
          title: '库存成本(元)',
          dataIndex: 'num',
        },
        {
          title: '零售价(元)',
          dataIndex: 'price',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      suppliercolumns: [
        {
          title: '供应商',
          dataIndex: 'name',
        },
        {
          title: '库存',
          dataIndex: 'count',
        },
        {
          title: '库存成本(元)',
          dataIndex: 'sum',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      channelcolumns: [
        {
          title: '渠道',
          dataIndex: 'name',
        },
        {
          title: '库存',
          dataIndex: 'count',
        },
        {
          title: '库存成本(元)',
          dataIndex: 'sum',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      brandcolumns: [
        {
          title: '品牌',
          dataIndex: 'name',
        },
        {
          title: '库存',
          dataIndex: 'count',
        },
        {
          title: '库存成本(元)',
          dataIndex: 'sum',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      classifycolumns: [
        {
          title: '分类',
          dataIndex: 'name',
        },
        {
          title: '库存',
          dataIndex: 'count',
        },
        {
          title: '库存成本(元)',
          dataIndex: 'sum',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      footerDataSource: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      pagination: {},
      optionParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
      },
      brandOption: [],
      classifyOption: [],
      loading: false,
      optionAlertShow: false,
    }
  },
  created() {
    this.handleSearch(this.queryParam)
    this.getBrandOption()
    this.getClassifyOption()
  },
  methods: {
    handleFooterShow() {
      if (this.footerDataSource.length > 0) {
        return (
          <a-table
            ref="table"
            size="default"
            rowKey={Math.random}
            pagination={false}
            columns={this.columns}
            dataSource={this.footerDataSource}
            showHeader={false}
            class="j-table-force-nowrap"
          ></a-table>
        )
      }
    },
    handleExpert(params) {
      exportSummaryUsingPOST({
        ...params,
        storeId: this.$route.params?.id,
        statisticType: this.operationActiveTabKey,
      }).then((res) => {
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=utf-8',
        })
        const filename = '库存统计详情列表' + '.xlsx'
        // 将blob对象转为一个URL
        var blobURL = window.URL.createObjectURL(blob)
        // 创建一个a标签
        var tempLink = document.createElement('a')
        // 隐藏a标签
        tempLink.style.display = 'none'
        // 设置a标签的href属性为blob对象转化的URL
        tempLink.href = blobURL
        // 给a标签添加下载属性
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        // 将a标签添加到body当中
        document.body.appendChild(tempLink)
        // 启动下载
        tempLink.click()
        // 下载完毕删除a标签
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
        this.$message.success('导出成功~')
      })
    },
    getBrandOption() {
      getGdBrandListUsingPOST(this.optionParam)
        .then((res) => {
          this.brandOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    getClassifyOption() {
      getGdClassListUsingPOST(this.optionParam)
        .then((res) => {
          this.classifyOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleSearch(params) {
      this.loading = true
      if (this.operationActiveTabKey === '2') {
        getPageGoodsSummaryUsingGET({
          ...params,
          storeId: this.$route.params?.id,
          statisticType: this.operationActiveTabKey,
        })
          .then((res) => {
            this.loadData = res.data.list.filter((item) => item.goodId)
            this.footerDataSource = res.data.list
              .filter((item) => !item.goodId)
              .map((item) => {
                return {
                  ...item,
                  goodName: '合计',
                }
              })
            console.log(this.footerDataSource)
            this.loading = false
            this.pagination = { ...this.pagination, total: Number(res.data.total) }
          })
          .catch((error) => {
            this.loading = false
            this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
          })
      } else {
        getPageSummaryUsingGET({
          ...params,
          storeId: this.$route.params?.id,
          statisticType: this.operationActiveTabKey,
        })
          .then((res) => {
            this.loadData = res.data.list.filter((item) => item.id)
            this.footerDataSource = res.data.list
              .filter((item) => !item.id)
              .map((item) => {
                return {
                  ...item,
                  name: '合计',
                }
              })
            this.loading = false
            this.queryParam.pageNo = this.pagination.current
            this.pagination = { ...this.pagination, total: Number(res.data.total) }
          })
          .catch((error) => {
            this.loading = false
            this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
          })
      }
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition: this.queryParam.queryCondition,
        status: this.queryParam.status,
        date: this.queryParam.date,
      })
    },
    handleDetail(record) {
      if (this.operationActiveTabKey === '1') {
        this.$router.push({
          path: `/stock/distribution/detail`,
          query: { storeId: this.$route.params?.id, stCounterId: record?.id },
        })
      } else if (this.operationActiveTabKey === '2') {
        this.$router.push({
          path: `/stock/distribution/detail`,
          query: { storeId: this.$route.params?.id, goodId: record?.goodId },
        })
      } else if (this.operationActiveTabKey === '3') {
        this.$router.push({
          path: `/stock/distribution/detail`,
          query: { storeId: this.$route.params?.id, supplyId: record?.id },
        })
      } else if (this.operationActiveTabKey === '4') {
        this.$router.push({
          path: `/stock/distribution/detail`,
          query: { storeId: this.$route.params?.id, channelId: record?.id },
        })
      } else if (this.operationActiveTabKey === '5') {
        this.$router.push({
          path: `/stock/distribution/detail`,
          query: { storeId: this.$route.params?.id, gdBrandId: record?.id },
        })
      } else if (this.operationActiveTabKey === '6') {
        this.$router.push({
          path: `/stock/distribution/detail`,
          query: { storeId: this.$route.params?.id, classId: record?.id },
        })
      }
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-table-content .ant-table-body {
  position: relative;
  z-index: 2;
  background: #ffffff;
}
/deep/ .ant-table-footer .ant-table-body {
  position: relative !important;
  z-index: 1 !important;
  overflow: hidden !important;
}
/deep/ .ant-table-content > .ant-table-footer {
  position: relative;
  top: -47px;
  z-index: 0;
  padding: 0 !important;
}
</style>
